package com.tangkeyon.service.impl;

import com.tangkeyon.common.Const;
import com.tangkeyon.common.ResponseCode;
import com.tangkeyon.common.TokenCache;
import com.tangkeyon.dao.UserMapper;
import com.tangkeyon.pojo.User;
import com.tangkeyon.service.IUserService;
import com.tangkeyon.util.MD5Util;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.UUID;

/**
 * @Author: tangkeyon@gmail.com
 * @Date: 2019/5/21 21:48
 * @Version 1.0
 */
@Service("iUserService")
public class IUserServiceImpl implements IUserService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public ResponseCode<User> login(String username, String password) {
        User user=null;
//        查询用户名是否存在
        int resNum = userMapper.checkUsername(username);
        if(resNum==0){
            return ResponseCode.createByErrorMessage("用户名不存在");
        }
         user = userMapper.selectLogin(username, MD5Util.MD5EncodeUtf8(password));
        if(user==null){
            return ResponseCode.createByErrorMessage("密码错误");
        }
//        为保证安全，传递给前台将密码置空
         user.setPassword(org.apache.commons.lang3.StringUtils.EMPTY);


         return ResponseCode.creatBySuccess(user,"登录成功");
    }


//    TODO 写法总结
    @Override
    public ResponseCode<String> checkValid(String value, String type) {
//        对传入的参数进行非空校验
        if(!org.apache.commons.lang3.StringUtils.isBlank(value)){
           if(Const.EMAIL.equals(type)){
               int resultCount = userMapper.checkEmail(value);
             if(resultCount>0){
                return ResponseCode.createByErrorMessage("邮箱已经存在");
             }
           }
           if(Const.USERNAME.equals(type)){
               int resultCode = userMapper.checkUsername(value);
               if(resultCode>0){
                  return ResponseCode.createByErrorMessage("用户名已经存在");
               }
           }
        }else{
            return ResponseCode.createByErrorMessage("参数错误");
        }
            return ResponseCode.creatBySuccessMessage("校验成功");
    }

    @Override
    public ResponseCode<String> registerUser(User user) {
//        对邮箱进行非空和存在性检验
        ResponseCode<String> responseValid = this.checkValid(user.getEmail(), Const.EMAIL);
         if(!responseValid.ifSuccess()){
             return responseValid;
         }

//        对用户名进行非空和存在性检验
         responseValid = this.checkValid(user.getUsername(), Const.USERNAME);
         if(!responseValid.ifSuccess()){
            return responseValid;
        }

         if(user.getPassword()==null){
             return  ResponseCode.createByErrorMessage("没有输入密码");
         }
//         对密码进行MD5加密
           user.setPassword(MD5Util.MD5EncodeUtf8(user.getPassword()));
//         设置为普通用户
           user.setRole(Const.Role.ROLE_CUSTOMER);
//         调用dao层方法进行注册
         int resultCount = userMapper.insert(user);
          if(resultCount==0){
              return ResponseCode.createByErrorMessage("注册失败");
          }
              return ResponseCode.creatBySuccessMessage("注册成功");
    }

    @Override
    public ResponseCode<String> getForgetQuestion(String username) {
//         对用户名进行非空和存在性检验
        ResponseCode<String> validResponse = this.checkValid(username, Const.USERNAME);
        if(validResponse.ifSuccess())
            return  ResponseCode.createByErrorMessage("用户名不存在");


        String question = userMapper.selectQuestionByUsername(username);
        if(org.apache.commons.lang3.StringUtils.isNotBlank(question)){
            return ResponseCode.creatBySuccess(question);
        }
        return ResponseCode.createByErrorMessage("用户名对应的密保问题为空");
    }

    @Override
    public ResponseCode<String> checkQuestionAnswer(String username, String question, String answer) {
        int resultCount = userMapper.checkQuestionAnswer(username, question, answer);
        if(resultCount==0){
            return ResponseCode.createByErrorMessage("问题回答错误");
        }
        //生成TOKEN并存入本地缓存
        String forgetToken= UUID.randomUUID().toString();
        TokenCache.setKey(TokenCache.TOKEN_PRIFIX+username,forgetToken);
        return ResponseCode.creatBySuccess(forgetToken);
    }

    @Override
    public ResponseCode<String> resizePassword(String username, String password, String token) {
//        参数校验
        ResponseCode<String> checkValid = this.checkValid(username, Const.USERNAME);
        if(checkValid.ifSuccess()){
            return ResponseCode.createByErrorMessage("用户名不存在");
        }
        if(org.apache.commons.lang3.StringUtils.isBlank(password)){
            return ResponseCode.createByErrorMessage("未输入密码");
        }
        if (org.apache.commons.lang3.StringUtils.isBlank(token)){
            return ResponseCode.createByErrorMessage("缺失Token");
        }

        String tokenKey=TokenCache.TOKEN_PRIFIX+username;
        String tokenValue = TokenCache.getKey(tokenKey);
        if(!org.apache.commons.lang3.StringUtils.equals(tokenValue,token)){
            return ResponseCode.createByErrorMessage("Token错误或过期");
        }

        String passwordMD5 = MD5Util.MD5EncodeUtf8(password);
        int resultCount = userMapper.updatePasswordByUsername(username, passwordMD5);
        if(resultCount==0){
            return ResponseCode.createByErrorMessage("重置密码错误");
        }
//        重置成功后将对应的token进行更换确保只能重置一次
        String forgetToken= UUID.randomUUID().toString();
        TokenCache.setKey(TokenCache.TOKEN_PRIFIX+username,forgetToken);

        return ResponseCode.creatBySuccessMessage("重置密码成功");
    }

    @Override
    public ResponseCode<String> changePasswordLoginState(String passwordNew, String passwordOld, Integer id) {
        if (StringUtils.isBlank(passwordNew)){
            return  ResponseCode.createByErrorMessage("未输入密码");
        }
        int resultCount = userMapper.selectPasswordById(MD5Util.MD5EncodeUtf8(passwordOld), id);
        if(resultCount==0){
            return  ResponseCode.createByErrorMessage("用户名与原始密码不匹配");
        }
           resultCount = userMapper.updatePasswordById(id,MD5Util.MD5EncodeUtf8(passwordNew));
        if(resultCount==0){
            return  ResponseCode.createByErrorMessage("修改密码失败");
        }
            return ResponseCode.createByErrorMessage("修改密码成功");
    }

    @Override
    public ResponseCode<User> selectUserInfoById(Integer id) {
        User user = null;

      user= userMapper.selectByPrimaryKey(id);

        if(user==null){
            return  ResponseCode.createByErrorMessage("该用户不存在");
        }
        user.setPassword(StringUtils.EMPTY);
        return ResponseCode.creatBySuccess(user);
    }

    @Override
    public ResponseCode<String> updateUserInformation(User user) {
//        更新用户信息，所修改的Email不能和其他用户的Email重复
        int resultCount = userMapper.checkEmailValid(user.getEmail(), user.getId());
        if(resultCount>0){
            return  ResponseCode.createByErrorMessage("邮箱重复，请更换邮箱");
        }

        User updateUser=new User();
        updateUser.setEmail(user.getEmail());
        updateUser.setAnswer(user.getAnswer());
        updateUser.setPhone(user.getPhone());
        updateUser.setUsername(user.getUsername());
        updateUser.setId(user.getId());

//        由于对象的有些属性为空，逻辑上只想对非空的属性对应的字段进行修改因此要使用该方法，
//        该方法内部使用动态sql，对参数进行非空检验只对非空的属性进行修改
        resultCount = userMapper.updateByPrimaryKeySelective(updateUser);
        if(resultCount==0){
            return  ResponseCode.createByErrorMessage("修改失败");
        }
            return  ResponseCode.createByErrorMessage("修改成功");
    }
}


























